<template>
  <!-- 故障部位设定表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1000px"
      draggable
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100">
        <div>
          <el-row v-show="!props.isReadonly">
            <!-- <el-col :span="24">
              <el-form-item label="部位类型" prop="positionType">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.positionType"
                  placeholder="请输入部位类型"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.positionType }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="设备" prop="equipIds">
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.equipIds"
                  placeholder="请选择设备"
                  clearable
                  filterable
                  multiple
                  collapse-tags
                  collapse-tags-tooltip
                  :max-collapse-tags="40"
                  class="select-device"
                >
                  <el-option
                    v-for="item in equipList"
                    :key="item.id"
                    :label="item.equipCode"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="设备种类" prop="assetTypeId">
                <el-tree-select
                  v-if="!props.isReadonly"
                  placeholder="请选择设备种类"
                  v-model="formData.assetTypeId"
                  :data="catalogList"
                  node-key="id"
                  :props="{
                    label: 'assetTypeName',
                    value: 'id',
                    children: 'nodes',
                  }"
                  :disabled="props.assetTypeId !== ''"
                  :render-after-expand="false"
                  :check-strictly="true"
                  style="width: 100%"
                  clearable
                  @change="changeEquipType"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备" prop="assetName">
                <el-input
                  :disabled="!formData.assetTypeId || props.assetTypeId !== ''"
                  v-model="formData.assetName"
                  placeholder="请选择设备"
                  @focus="openSelectDialog()"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="部位编号" prop="positionCode">
                <el-input
                  v-model="formData.positionCode"
                  placeholder="请输入部位编号"
                  clearable
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="部位名称" prop="positionName">
                <el-input
                  v-model="formData.positionName"
                  placeholder="请输入部位名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="序号" prop="sort">
                <el-input
                  v-model="formData.sort"
                  placeholder="请输入序号"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用状态" prop="enabled">
                <el-radio-group v-model="formData.enabled">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-descriptions
            v-show="props.isReadonly"
            class="mb-[10px]"
            :column="3"
            border
          >
            <el-descriptions-item :span="1">
              <template #label>
                <div class="cell-item">设备种类</div>
              </template>
              <div style="width: 100%; word-break: break-all">
                {{ formData.assetTypeName }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">设备名称</div>
              </template>
              <div style="width: 100%; word-break: break-all">
                {{ formData.assetName }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">设备编码</div>
              </template>
              <div style="width: 100%; word-break: break-all">
                {{ formData.assetCode }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">部位编号</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.positionCode }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">部位名称</div>
              </template>

              <div style="width: 100%; word-break: break-all">
                {{ formData.positionName }}
              </div>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">排序</div>
              </template>
              {{ formData.sort }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">是否启用</div>
              </template>
              <el-tag v-show="formData.enabled === 1" type="">启用</el-tag>
              <el-tag v-show="formData.enabled !== 1" type="info">停用</el-tag>
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item">创建时间</div>
              </template>
              {{ formData.createTime }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">创建人</div>
              </template>
              {{ formData.createdUserName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">更新时间</div>
              </template>
              {{ formData.lastUpdateTime }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">更新人</div>
              </template>
              {{ formData.lastUpdatedUserName }}
            </el-descriptions-item>
            <el-descriptions-item :span="2">
              <template #label>
                <div class="cell-item">备注</div>
              </template>
              <div style="width: 100%; word-break: break-all">
                {{ formData.remarks || "暂无备注" }}
              </div>
            </el-descriptions-item>
          </el-descriptions>

          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 10px;
            "
          >
            <h4 class="mb-[0px] mt-[0px]">部位组成</h4>
            <el-button
              v-show="!props.isReadonly"
              type="success"
              plain
              @click="handleAdd(formData.nodes)"
            >
              <i-ep-plus />
              新增
            </el-button>
          </div>
          <!-- <div>
            <h4 class="mb-[20px] mt-[20px]">部位组成</h4>
          </div>
          <div>
            <el-button
              v-show="!props.isReadonly"
              plain
              style="margin-bottom: 10px"
              type="success"
              @click="handleAdd(formData.nodes)"
            >
              <i-ep-plus/>
              新增
            </el-button>
          </div> -->
          <div class="formTable">
            <el-table
              :data="formData.nodes"
              border
              style="width: 100%"
              row-key="id"
              highlight-current-row
              max-height="250px"
              :tree-props="{ children: 'nodes', hasChildren: 'hasChildren' }"
            >
              <el-table-column
                label="部位编号"
                min-width="150"
                props="positionCode"
                header-align="center"
                show-overflow-tooltip
              >
                <template #default="{ $index, row }">
                  <span>{{ row.positionCode }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="部位名称"
                min-width="150"
                props="positionName"
                header-align="center"
                show-overflow-tooltip
              >
                <template #default="{ $index, row }">
                  <span>{{ row.positionName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="序号"
                min-width="80"
                props="sort"
                align="center"
                header-align="center"
              >
                <template #default="{ $index, row }">
                  <div class="align-center">{{ row.sort }}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="启用状态"
                min-width="90"
                props="sort"
                align="center"
                header-align="center"
              >
                <template #default="{ $index, row }">
                  <el-tag v-if="row.enabled === 1" type="success" size="small">
                    启用
                  </el-tag>
                  <el-tag v-else type="info" size="small"> 停用 </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                min-width="100"
                props="remarks"
                header-align="center"
                show-overflow-tooltip
              >
                <template #default="{ $index, row }">
                  <span>{{ row.remarks }}</span>
                </template>
              </el-table-column>

              <el-table-column
                v-if="!props.isReadonly"
                align="center"
                fixed="right"
                label="操作"
                width="150"
                header-align="center"
              >
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    @click.stop="subAddRow(scope.row)"
                  >
                    <i-ep-plus />
                  </el-button>
                  <el-button type="primary" link @click="editRow(scope.row)">
                    <i-ep-edit />
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    @click.stop="handleDelete(scope.row)"
                  >
                    <i-ep-delete />
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <componentGroup-edit
      :visible="groupDialog.visible"
      :title="groupDialog.title"
      :data="groupDialog.data"
      :type="groupDialog.type"
      :is-readonly="groupDialog.readvisible"
      @change-visible="changeVisible"
      @submit="nodesubmit"
      @edit="groupEdit"
      @subAdd="subAdd"
    />
    <SelectDeviceDialog-Eam
      v-model:visible="selectDialog.visible"
      :data="selectDialog.data"
      :assetTypeId="formData.assetTypeId"
      :isMultiple="false"
      @echo-info="changeVisible1"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { getMdmProcessEquipApi1 } from "@/utils/commonData"; // 引入
import { deepClone } from "@/utils/commonHooks";
// import efafaultgroupEdit from "./efafaultgroup-edit.vue";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ComponentPartEdit",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  parentId: {
    type: String,
    default: () => {
      return "";
    },
  },
  assetTypeId: {
    type: String,
    default: () => {
      return "";
    },
  },
  assetKind: {
    type: Number,
    default: 1,
  },
});

//  点击设备
function openSelectDialog() {
  selectDialog.visible = true;
  selectDialog.data = formData.assetId
    ? [
        {
          id: formData.assetId,
          assetName: formData.assetName,
          assetCode: formData.assetCode,
        },
      ]
    : [];
}
//设备显隐
const selectDialog = reactive<DialogOption>({
  visible: false,
  data: [],
});
// 设备选择确认后的回调函数
const changeVisible1 = (options: any) => {
  if (options && options.length) {
    const data = options[0];
    formData.assetId = data.id;
    formData.assetCode = data.assetCode;
    formData.assetName = data.assetName;
  } else {
    formData.assetId = "";
    formData.assetCode = "";
    formData.assetName = "";
  }
};

function changeEquipType() {
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
}

const subAdd1 = ref(false);

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
    // if (newVal) {
    //   getEquipList({});
    // }
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  equipIds: [],
  details: [],
  nodes: [],
  version: "",
  assetKind: "",
  assetTypeId: "",
  assetTypeName: "",
  assetBrandId: "",
  assetModelId: "",
  assetModelNo: "",
  positionCode: "",
  positionName: "",
  sort: "1",
  parentId: "0",
  allId: "",
  allCode: "",
  allName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  // 设备信息
  assetId: "",
  assetName: "",
  assetCode: "",
});

function validateDegree(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入整数"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else if (Number(value) < 0) {
    callback(new Error("请输入大于0的整数"));
  } else {
    callback();
  }
}
/** rules规则 */
const rules = reactive({
  assetTypeId: [
    { required: true, message: "请选择设备种类", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "change" },
  ],
  positionCode: [
    { required: true, message: "请输入部位编号", trigger: "blur" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  positionName: [
    { required: true, message: "请输入部位名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sort: [
    { required: true, message: "请输入序号", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  positionType: [
    { required: true, message: "请输入部位类型", trigger: "blur" },
  ],
  equipIds: [{ required: true, message: "请选择设备", trigger: "blur" }],
});

const isValidated = ref(false);
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        // getdetails();
        getnodes();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.equipIds = [];
  formData.nodes = [];
  formData.id = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.lastUpdateTime = "";
  formData.version = "";
  formData.assetKind = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.assetBrandId = "";
  formData.assetModelId = "";
  formData.assetModelNo = "";
  formData.positionCode = "";
  formData.positionName = "";
  formData.sort = "1";
  formData.parentId = "0";
  formData.allId = "";
  formData.allCode = "";
  formData.allName = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.assetId = "";
  formData.assetName = "";
  formData.assetCode = "";
  subAdd1.value = false;
}

const loading = ref(false);

function processArr(arr) {
  arr.forEach((item) => {
    if (item.id && item.id.length === 8) {
      item.id = "";
    }
    if (Array.isArray(item.nodes)) {
      processArr(item.nodes);
    }
  });
}

/** 故障部位设定保存提交 */
function handleSubmit() {
  console.log("formData", toRaw(formData));
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      formData.parentId = !formData.id ? "0" : formData.parentId;
      const text = formData.id ? "编辑" : "新增";
      formData.details = formData.equipIds.map((item: any) => {
        const find = equipList.value.find((equip) => equip.id === item);
        return {
          equipCode: find?.equipCode,
          equipName: find?.equipName,
          equipId: item,
        };
      });

      const list = deepClone(formData);
      processArr(list.nodes || []);
      await request({
        url: "/eam/eamassetposition/saveNew",
        method: "post",
        data: list,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/eamassetposition/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  formData.equipIds = sondetails.data.map((item: any) => item.equipId);
  formData.equipCodes = sondetails.data
    .map((item: any) => item.equipCode)
    .join(",");
}
async function getnodes() {
  let sondetails = await request({
    url: "/eam/eamassetposition/getTreeNew",
    method: "post",
    data: {
      size: 10,
      current: 1,
      data: {
        id: formData.id,
      },
    },
  }).finally(() => {
    loading.value = false;
  });
  formData.nodes = sondetails.data;
}

// 通过工序查询设备列表
const equipList = ref(<any>[]);

async function getEquipList(params: Object) {
  equipList.value = (await getMdmProcessEquipApi1(params)) || [];
}

const nodes: any = {
  id: "",
  faultPositionId: "",
  position: "",
  keyword: "",
  parentId: "",
  allId: "",
  allPosition: "",
  allKeyword: "",
  deleted: "",
  enabled: 1,
  ids: [],
  nodes: [],
  version: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = (roleObj?: Object) => {
  groupDialog.title = "新增子组成部位";
  groupDialog.type = "submit";
  groupDialog.row = roleObj;
  groupDialog.visible = true;
  groupDialog.readvisible = false;
};

/** 添加行 */
const subAddRow = (roleObj?: Object) => {
  groupDialog.title = "新增子组成部位";
  groupDialog.type = "subAdd";
  groupDialog.row = roleObj;
  rowData.value = roleObj;
  groupDialog.visible = true;
  groupDialog.readvisible = false;
};

const rowData = ref();
const editRow = (roleObj?: Object) => {
  groupDialog.title = "修改子组成部位";
  groupDialog.type = "edit";
  groupDialog.data = roleObj;
  rowData.value = roleObj;
  groupDialog.visible = true;
  groupDialog.readvisible = false;
};
const handleDelete = (target) => {
  const result = findParent(formData.nodes, target.id);
  if (result) {
    const { parent, index } = result;
    if (parent) {
      parent.nodes.splice(index, 1);
    } else {
      formData.nodes.splice(index, 1);
    }
  }
};

// 递归查找父节点
const findParent = (data, targetId, parent = null) => {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === targetId) {
      return { parent, index: i };
    }
    if (data[i].nodes?.length) {
      const result = findParent(data[i].nodes, targetId, data[i]);
      if (result) return result;
    }
  }
};

const groupDialog = reactive<DialogOption & { row: any; type: string }>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  row: {},
  type: "",
});
function changeVisible(value: boolean) {
  groupDialog.visible = value;
  if (!value) {
    groupDialog.data = {};
  }
}
function nodesubmit(value: any) {
  groupDialog.visible = false;
  groupDialog.row.push(value);
  groupDialog.row = {};
}

function groupEdit(value: any) {
  groupDialog.visible = false;
  Object.assign(rowData.value, value);
  rowData.value = {};
  groupDialog.data = {};
}
function subAdd(value: any) {
  groupDialog.visible = false;
  if (rowData.value.nodes) rowData.value.nodes.push(value);
  else rowData.value.nodes = [value];
  rowData.value = {};
  groupDialog.data = {};
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/equAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
  });
};

onMounted(() => {
  getCAtalogList();
});
</script>
<style lang="scss" scoped>
// :deep(.el-table__body-wrapper .cell) {
//   display: flex !important;
//   align-items: center !important;
// }
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  //   max-height: 65vh;
  padding: 20px;
}
:deep(.el-descriptions__label) {
  white-space: nowrap !important;
}
h4 {
  font-weight: 600;
  color: #666;
  font-size: 15px;
  line-height: 15px;
  padding-top: 10px;
}
:deep(.select-device) {
  .el-tag {
    padding: 0 4px;
  }
}
:deep(.el-select__tags) {
  flex-wrap: nowrap;
}
</style>
